package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import pojo.User;
import service.UserService;
import service.factory.UserServiceFactory;
import dto.JsonResult;


@Controller
@RequestMapping("/user")
public class UserController{
	private UserService service;
	
	public UserController() {
		service = UserServiceFactory.getInstance();
	}
	
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public @ResponseBody JsonResult add(User user){
		JsonResult result = null;
		User u = service.addUser(user);
		if(u != null){
			result = new JsonResult(200,"success",u);
		}else{
			result = new JsonResult(500,"failure",null);
		}
		return result;
	}
	
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public @ResponseBody JsonResult update(User user){
		JsonResult result = null;
		User u = service.updateUser(user);
		if(u != null){
			result = new JsonResult(200,"success",u);
		}else{
			result = new JsonResult(500,"failure",null);
		}
		return result;
	}
	
	@RequestMapping(value="/{id}/delete", method=RequestMethod.POST)
	public @ResponseBody JsonResult delete(@PathVariable("id") String id){
		JsonResult result = null;
		if("success".equals(service.deleteUser(id))){
			result = new JsonResult(200,"success",null);
		}else{
			result = new JsonResult(500,"failure",null);
		}
		return result;
	}
	
	@RequestMapping(value="/listAll")
	public @ResponseBody JsonResult queryAllUser(Model model){
		JsonResult result = new JsonResult(200, "success", service.queryAllUser());
		return result;
	}
	
	public String upload(MultipartFile file){

		return "suc";
	}

}
